import axios, {
  AxiosInstance,
  InternalAxiosRequestConfig,
  // AxiosRequestHeaders,
  AxiosResponse,
  AxiosError
} from 'axios'

// import qs from 'qs'
import { get } from 'lodash-es'
import { config } from './config'

import { showToast } from 'vant'
import { useCache, tokenKey } from '@/hooks/web/useCache'
import { getHotelCode, getOpenId } from '@/utils'

const { result_code, base_url } = config
const { wsCache } = useCache()

export const PATH_URL = base_url[import.meta.env.VITE_API_BASEPATH]

// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: PATH_URL, // api 的 base_url
  timeout: config.request_timeout // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = wsCache.get(tokenKey)
    const openid = getOpenId()

    if (token) {
      config.headers.Authorization = `Bear ${token}`
    }

    if (openid) {
      config.headers.openid = openid
    }

    config.headers.hotelcode = getHotelCode()

    return config
  },
  (error: AxiosError) => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  (response: AxiosResponse<any>) => {
    if (response.config.responseType === 'blob') {
      // 如果是文件流，直接过
      return response
    } else if (response.data.errCode === result_code) {
      return response.data
    } else {
      showToast(response.data.errMsg)
    }
  },
  (error: AxiosError) => {
    console.log('err' + error) // for debug
    const res_status = get(error, 'response.status')
    if (res_status === 401) {
      showToast('未登录')
    } else if (res_status === 403) {
      showToast('登录信息过期，请重新登录！')
    } else {
      showToast(error.message)
    }

    return Promise.reject(error)
  }
)

export { service }
